local skynet = require "skynet"
local message_packet = require "common.message_packet"
local proto_manager = require "common.proto_manager"
local watchdog_proxy = require "agents.watchdog_proxy"
local msg_center = require "common.msg_center"

local HeartBetMessageId = proto_manager.message_id("MessageId_None")

local recvMsgFilter = nil

local client_msg_handlers = {}
local watchdog_msg_handlers = {}

function msg_center.setRecvMsgFilter(handler)
    recvMsgFilter = handler
end

function msg_center.setClientMessageHandler(id,handler,enable)
    id = tonumber(id) or 0
    return msg_center.setMessageHandler(client_msg_handlers,id,handler,enable)
end

function msg_center.setWatchdogMessageHandler(id,handler,enable)
    return msg_center.setMessageHandler(watchdog_msg_handlers,id,handler,enable)
end

function msg_center.dispatchWatchdogMessage(id,...)
    msg_center.dispatchMessage(watchdog_msg_handlers,id,...)
end

function msg_center.clearAll()
    msg_center.clearAllDefault()
    client_msg_handlers = {}
    watchdog_msg_handlers = {}
end

skynet.register_protocol {
    name = "client",
    id = skynet.PTYPE_CLIENT,
    unpack = function (msg, sz)
        local header,err = message_packet.unpack(msg,sz)
        return header,err
    end,
    dispatch = function (fd, _, header,err)
        if err then
            pcall(watchdog_proxy.disconnect,fd)
            skynet.error("unpack message header faild! err:" .. tostring(err) .. " fd:" .. fd)
            return
        end
        local id = header.id
        if recvMsgFilter then
            recvMsgFilter(fd,id)
        end
        if id ~= HeartBetMessageId then
            msg_center.dispatchMessage(client_msg_handlers,id,fd,id,header.data)
        end
    end
}

return msg_center